let departmentAddModule = (function () { 
    let $submit = $('.submit'),
        $departName = $('.departName'),
        $departDesc = $('.departDesc'),
        $spanDepartName =$('.spanDepartName')
    let departId = null
    function checkName() {
        let val = $departName.val().trim()
        if (val.length === 0) {
            $spanDepartName.html('请输入部门名称')
            return false
        }
        return true
    }
    
    async function submitHandle() { 
        if (!checkName()) return
        let params = {
            name:$departName.val().trim(),
            desc:$departDesc.val().trim()
        }
        if (departId) {
            params.departmentId = departId
            let result =await axios.post('/department/update', params)
            if (result.code == 0) {
                localStorage.removeItem('department')
                alert('修改成功')
                window.location.href = 'departmentlist.html'
                return
            }
            return
        }
        let result =await axios.post('/department/add', params)
        if (result.code == 0) {
            localStorage.removeItem('department')
            alert('添加成功')
            window.location.href = 'departmentlist.html'
            return
        }
        alert('添加失败')
    }
    async function queryBaseInfo() {
        let result = await axios.get('/department/info', {
            params: {
                departmentId:departId
            }
        })
        if (result.code == 0) {
            let {name,desc} = result.data
            $departName.val(name)
            $departDesc.val(desc)
            return
        }
        alert('当前编辑的部门不存在，请查证！')
        window.location.href='departmentlist.html'
    }
    return {
        init() {
            let params = window.location.href.queryURLParams()
            if (params.hasOwnProperty('departId')) {
                departId = params.departId
                queryBaseInfo()
            } 

            $departName.blur(checkName)
            $submit.click(submitHandle)    
        }
    }
})()
departmentAddModule.init()